// 这个脚本只在本地开发环境运行，不会被部署到 Workers
const fs = require('fs');
const path = require('path');
const handlebars = require('handlebars');

// 使用绝对路径避免Windows路径问题
const baseTemplatePath = path.resolve(__dirname, 'src', 'templates', 'base.html');
const shareTemplatePath = path.resolve(__dirname, 'src', 'templates', 'share.html');
const fileShareTemplatePath = path.resolve(__dirname, 'src', 'templates', 'fileShare.html');

// 读取模板文件，指定编码为utf8
let baseTemplate, shareTemplate, fileShareTemplate;
try {
  baseTemplate = fs.readFileSync(baseTemplatePath, 'utf8');
  shareTemplate = fs.readFileSync(shareTemplatePath, 'utf8');
  fileShareTemplate = fs.readFileSync(fileShareTemplatePath, 'utf8');
} catch (error) {
  console.error('读取模板文件失败:', error.message);
  process.exit(1);
}

// 移除可能的BOM标记
baseTemplate = baseTemplate.replace(/^\ufeff/, '');
shareTemplate = shareTemplate.replace(/^\ufeff/, '');
fileShareTemplate = fileShareTemplate.replace(/^\ufeff/, '');

// 预编译模板
let compiledBaseTemplate, compiledShareTemplate, compiledFileShareTemplate;
try {
  compiledBaseTemplate = handlebars.precompile(baseTemplate);
  compiledShareTemplate = handlebars.precompile(shareTemplate);
  compiledFileShareTemplate = handlebars.precompile(fileShareTemplate);
} catch (error) {
  console.error('预编译模板失败:', error.message);
  process.exit(1);
}

// 生成编译后的模板文件
const outputDir = path.resolve(__dirname, 'src', 'templates', 'compiled');
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

// 输出为 ES 模块格式
const baseOutputPath = path.resolve(outputDir, 'base.js');
const shareOutputPath = path.resolve(outputDir, 'share.js');
const fileShareOutputPath = path.resolve(outputDir, 'fileShare.js');

try {
  fs.writeFileSync(
    baseOutputPath,
    `export default ${compiledBaseTemplate};
`
  );

  fs.writeFileSync(
    shareOutputPath,
    `export default ${compiledShareTemplate};
`
  );

  fs.writeFileSync(
    fileShareOutputPath,
    `export default ${compiledFileShareTemplate};
`
  );

  console.log('模板预编译成功!');
} catch (error) {
  console.error('写入编译后的模板文件失败:', error.message);
  process.exit(1);
}